package com.skynet.supervision.aop.validate;

import com.skynet.supervision.utils.Strings;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

public class GoodStringValidator implements ConstraintValidator<GoodString, String> {

    private GoodString anno;

    @Override
    public void initialize(GoodString constraintAnnotation) {
        anno = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Objects.requireNonNull(anno);
        if (anno.required() && value == null) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("不可为null")
                    .addConstraintViolation();
            return false;
        }
        if (value != null && anno.noSpace() && value.contains(" ")) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("不可以包含任意空白字符")
                    .addConstraintViolation();
            return false;
        }
        if (value != null && anno.noEmpty() && Strings.isEmpty(value)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("不可以是空字符串")
                    .addConstraintViolation();
            return false;
        }
        return true;
    }
}
